package DAO;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import Beans.Admin;
import Utils.HibernateUtil;

public class AdminDao {

	Transaction tr = null;
	private SessionFactory sessionFactory;

	/**
	 * 通过管理员ID返回指定管理员信息
	 * 
	 * 管理员ID
	 * 
	 * @return
	 */
	public Admin getAdminById(int adminId) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		Admin admin = (Admin) session.get(Admin.class, adminId);
		tr.commit();
		session.close();
		return admin;
	}

	/**
	 * 删除管理员
	 */
	public void delete(Admin admin) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.delete(admin);
		tr.commit();
		session.close();
	}

	/**
	 * 修改管理员
	 */
	public void edit(Admin admin) {
		Session session = sessionFactory.openSession();
		tr = session.beginTransaction();
		session.update(admin);
		tr.commit();
		session.close();
	}

	public Admin get(String username, String password) {

		Session session = sessionFactory.openSession();
		Admin admin = null;

		tr = session.beginTransaction();
		Criteria c = session.createCriteria(Admin.class);
		c.add(Restrictions.eq("username", username));
		c.add(Restrictions.eq("password", password));
		List<Admin> result = c.list();
		if (result.iterator().hasNext()) {
			admin = (Admin) result.iterator().next();
		}

		tr.commit();

		session.close();
		return admin;

	}

	public void save(Admin admin) {
		Session session = sessionFactory.openSession();

		tr = session.beginTransaction();
		session.save(admin);
		tr.commit();
		session.close();

	}

	public List<Admin> getAll() {
		Session session = sessionFactory.openSession();

		tr = session.beginTransaction();
		Criteria c = session.createCriteria(Admin.class);
		List<Admin> admins = c.list();
		tr.commit();

		session.close();
		return admins;
	}

	public List<Admin> adminLogin(String username, String password) {
		Session session = sessionFactory.openSession();

		tr = session.beginTransaction();
		Criteria c = session.createCriteria(Admin.class);
		c.add(Restrictions.eq("username", username));
		c.add(Restrictions.eq("password", password));
		List<Admin> admins = c.list();
		tr.commit();

		session.close();
		return admins;
	}

	public AdminDao() {
		sessionFactory = HibernateUtil.getSessionFactory();
	}
}
